//创建一个数组用来临时放商品id和商品数量
let goodList = [];
let goodNum = [];
//放商品的总价
let totalList = [];
//复选框被选中的个数
let all = 0;
//删除一件商品
function del(index){
	let goodsId = goodList[index];
	ajax({
		method:"POST",
		url:BASE_URL+"/api_cart",
		type:"JSON",
		params:"userId="+userId+"&goodsId="+goodsId+"&status=delcart",
		callback:function(data){
			console.log(data.message);
		}
	})
	renderGoodsTab();
}

//复选框选中
function sel(index){
	let checkbox = document.querySelector(`input[id='checkbox${index}']`);
	let box = document.querySelector("input[id='checkbox']");
	let totals = document.querySelector("#total");
	if(checkbox.checked){
		total += totalList[index];
		all += 1;
	}
	else{
		total -= totalList[index];
		all -= 1;
	}
	totals.innerHTML = total.toFixed(2);
	if(all == totalList.length){
		box.checked = true;
	}
	else{
		box.checked = false;
	}
}

//全选
function selAll(){
	let totalPrice = 0;
	let totals = document.querySelector("#total");
	let box = document.querySelector("input[id='checkbox']");
	let checkbox = document.querySelectorAll("input[class='checkbox']");
	if(box.checked){
		totalList.forEach((item,index)=>{
			checkbox[index+1].checked = true;
			totalPrice += item;
		})
		totals.innerHTML = totalPrice.toFixed(2);
	}
	else{
		totalList.forEach((item,index)=>{
			checkbox[index+1].checked = false;
		})
		totals.innerHTML = 0.00;
	}
}

//减少商品数量
function subNum(index){
	let goodsId = goodList[index];
	let number = goodNum[index];
	if(number>1){
		ajax({
			method: "POST",
			url: BASE_URL + "/api_cart",
			type: "JSON",
			params: "userId=" + userId + "&goodsId=" + goodsId + "&goodsNumber=" + (parseInt(number) - 1) +"&status=addcart",
			callback:function(data){
				renderGoodsTab();
			}
		})
		renderGoodsTab();
	}else{
		return;
	}
}
//增加商品数量
function addNum(index){
	let goodsId = goodList[index];
	let number = goodNum[index];
	ajax({
		method: "POST",
		url: BASE_URL + "/api_cart",
		type: "JSON",
		params: "userId=" + userId + "&goodsId=" + goodsId + "&goodsNumber=" + (parseInt(number) + 1) +"&status=addcart",
		callback:function(data){
			renderGoodsTab();
		}
    })
}

//渲染购物车的商品表格
function renderGoodsTab(){
	goodList=[];
	goodNum = [];
	totalList = [];
	ajax({
		method: "POST",
		url: BASE_URL + "/api_cart",
		type: "JSON",
		params: "userId=" + userId + "&status=viewcart",
		callback: function(data) {
			let list = data.data;
			let itemList = document.querySelector(".shopTab>tbody");
			let text = '';
			list.forEach((item,index) => {
				const totalPrice = item.price * parseInt(item.goods_number);
				goodList.push(item.goods_id);
				goodNum.push(item.goods_number);
				totalList.push(totalPrice);
				text += "<tr class='itemList'>" +
					"<td>" +
					"<input type='checkbox' class='checkbox' id='checkbox"+index+"' onclick='sel("+index+")'>" +
					"<a href='goodDetails.html?goodsId="+item.goods_id+"' class='shopImg'>" +
					"<img src='"+item.goods_thumb+"'>" +
					"</a>" +
					"</td>" +
					"<td class='itemName'>" +
					"<p>" +
					"<a href='goodDetails.html?goodsId="+item.goods_id+"'>"+item.goods_name+"</a>" +
					"</p>" +
					"</td>" +
					"<td>" +
					"<a href='#' class='sub' onclick='subNum("+index+")'>" +
					"<img src='img/sub.png'>" +
					"</a>" +
					"<input id='item("+index+")' type='text' readonly value='"+item.goods_number+"' class='itemNum'>" +
					"<a href='#' class='add' onclick='addNum("+index+")'>" +
					"<img src='img/add.png'>" +
					"</a>" +
					"</td>" +
					"<td>"+item.price+"</td>" +
					"<td>"+totalPrice+"</td>" +
					"<td>" +
					"<a href='#' class='cartDel' onclick='del("+index+")'>删除</a>" +
					"</td>" +
					"</tr>"
			})
			itemList.innerHTML = text;
		}
	})
}


window.onload = function() {
	renderGoodsTab();
	let payBtn = document.querySelector("button[class='payBtn']");
	payBtn.addEventListener("click",()=>{
		//获得被选中的商品的商品id加入结算清单
		// 获取所有 checkbox
		const checkboxes = document.querySelectorAll('.itemList input[type="checkbox"]');
		// 遍历 checkbox，找出被选中的索引
		const selectedIndexes = Array.from(checkboxes)
		    .map((checkbox, index) => checkbox.checked ? index : -1)
		    .filter(index => index !== -1);
		
		// 通过索引获取对应的商品 ID
		const selectedProductIds = selectedIndexes.map(index => goodList[index]);
		console.log(selectedProductIds);
	    let goodIdList = selectedProductIds[0];
		for(i=1; i<selectedProductIds.length; i++){
			goodIdList += "&"+selectedProductIds[i];
			console.log(goodIdList);
		}
		ajax({
			method:"POST",
			url:BASE_URL+"/api_settlement",
			type:"JSON",
			params:"userId="+userId+"&from=cart&goodsId="+encodeURIComponent(selectedProductIds.join('&'))+"&status=addsettlement",
			callback:function(data){
				window.location.href = 'settlement.html';
			}
		})
	})
}